package hhm.android.machine.bluetooth

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import hhm.android.library.utils.OnMultiClickListener
import hhm.android.library.utils.SpacesItemDecoration
import hhm.android.machine.BindThreeAdapter
import hhm.android.machine.MachineConnectFailActivity
import hhm.android.machine.MatchSuccessActivity
import hhm.android.machine.R
import siau.android.base.*
import siau.android.http.model.AddMachineRequest
import siau.android.http.model.BluetoothCodeModel
import siau.android.library.KeyString

class BindToothBrushThreeActivity : SBBaseActivity() {

    lateinit var recycler: RecyclerView
    lateinit var startActivityForResult: ActivityResultLauncher<Intent>
    private val list = ArrayList<MyBlueToothBean>()
    private var b: MyBlueToothBean? = null
    private var childId: Int = -1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setTitleWhiteAndTextBlank()
        setContentView(R.layout.activity_bind_toothbrush_three)

        initTitleWithLine(getString(R.string.seven_bubble_height_machine))

        childId = intent.getIntExtra(KeyString.childId, -1)
        if (childId == -1) {
            showToast(getString(R.string.please_select_match_toothbrush_baby))
            finish()
        }

        recycler = findViewById(R.id.activity_bind_toothbrush_three_recycler)

        startActivityForResult = registerForActivityResult(IntentIntActivityResultContact()) {
            if (it == 1024) {
                setResult(1024)
                finish()
            }
        }

        recycler.layoutManager = LinearLayoutManager(this)
        recycler.addItemDecoration(SpacesItemDecoration(16))
        SBApplication.getBlueToothUtils().scanDevices!!.forEach {
            if (it.deviceType == 3 && !list.contains(it)) {
                list.add(it)
            }
        }
        recycler.adapter = BindThreeAdapter(list, object : OnMultiClickListener() {
            override fun onMultiClick(v: View?) {
                b = v?.tag as MyBlueToothBean
                showLoadingDialog()
                val r = BluetoothCodeModel(b!!.bluetoothCode)
                HttpHelper().checkCanBindBluetooth(r)?.subscribe({
                    if (it.isExist == 1) {
                        hideLoadingDialog()
                        showToast(getString(R.string.device_is_bounded))
                    } else {
                        SBApplication.getBlueToothUtils().setCallback(bCallBack)
                        SBApplication.getBlueToothUtils().connect(b, true)
                        handler.sendEmptyMessageDelayed(0, 15000)
                    }
                }, {
                    hideLoadingDialog()
                    showToast(it.message)
                })
            }
        })

        SBApplication.getBlueToothUtils().scanDevicesNum?.observe(this, {
            SBApplication.getBlueToothUtils().scanDevices!!.forEach {
                if (it.deviceType == 3 && !list.contains(it)) {
                    list.add(it)
                }
            }
            recycler.adapter?.notifyDataSetChanged()
        })
    }

    fun goToFailPage() {
        val i = Intent(this, MachineConnectFailActivity::class.java)
        startActivityForResult.launch(i)
    }

    fun goToSuccessPage() {
        val i = Intent(this, MatchSuccessActivity::class.java)
        i.putExtra(KeyString.type, 3)
        startActivityForResult.launch(i)
    }

    val bCallBack = object : BlueToothUtil.CallBack {
        override fun hasConnect() {
            hideLoadingDialog()
            goToFailPage()
            showToast("设备已被连接")
        }

        override fun connectSuccess(myBlueToothBean: MyBlueToothBean) {
            if (b != null && b!!.bluetoothCode == myBlueToothBean.bluetoothCode) {
                val r = AddMachineRequest(3, myBlueToothBean.bluetoothCode, 1, 0, myBlueToothBean.bluetoothCode, 2, childId)
                HttpHelper().addDevice(r)?.subscribe({
                    SBApplication.userData.footGuide = it.footGuide
                    SBApplication.userData.deviceList = it.deviceList
                    hideLoadingDialog()
                    handler.removeMessages(0)
                    SBApplication.getBlueToothUtils().scanDevices?.clear()
                    SBApplication.getBlueToothUtils().scanDevicesNum?.value = 0
                    SBApplication.getBlueToothUtils().setCallback(null)
                    goToSuccessPage()
                }, {
                    hideLoadingDialog()
                    showToast(it.message)
                })
            }
        }

        override fun connectFail() {
            hideLoadingDialog()
            goToFailPage()
            handler.removeCallbacksAndMessages(null)
            showToast("设备连接失败")
        }
    }

    override fun finish() {
        SBApplication.getBlueToothUtils().setCallback(null)
        super.finish()
    }

    val handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            SBApplication.getBlueToothUtils().cancelConnect()
            hideLoadingDialog()
            goToFailPage()
            showToast("设备连接失败")
        }
    }
}